//
//  TKIMSMSChatView.m
//  test2
//
//  Created by TryHone on 16/7/18.
//  Copyright © 2016年 TryHone. All rights reserved.
//

#import "TKIMSMSChatView.h"
#import "TKIMAudioMsgView.h"
#import "TKIMTableView.h"
#import "TKIMRefreshHeaderView.h"
#import "TKIMRefreshFooterView.h"
#import "TKIMAcceptOrderTip.h"

@interface TKIMSMSChatView()<UITableViewDataSource,UITableViewDelegate,TKIMToolBarDelegate,TKIMAudioDelegate,TKIMTableViewDelegate,UIActionSheetDelegate>

//@property(nonatomic,strong) TKIMTableView *tableView;
@property(nonatomic,strong) NSMutableArray *dataSource;//数据源
@property(nonatomic,strong) TKIMToolBar *toolBar;//工具栏
@property(nonatomic,strong) TKIMAudioHelper *audioHelper;//声音工具对象
@property(nonatomic,strong) TKIMAudioMsgView *currentAudio;//当前声音播放的对象
@property (strong, nonatomic) NSDate *chatTagDate;
@property(strong,nonatomic) TKIMMessage *selectMessage;
@property(nonatomic,strong) TKIMMenuBar *menuBar;//工具栏
@property(nonatomic,assign) TKIMToolBarType toolBarType;

@property(nonatomic,strong) UIButton * deleteBtn;  //删除按钮

@property(nonatomic,strong) NSDictionary *emotion;

@property (nonatomic,strong)TKIMRefreshHeaderView * refreshHeader;
@property (nonatomic,strong)TKIMRefreshFooterView * refresfooter;
@property(nonatomic,weak)TKIMAcceptOrderTip * tip;

@property(nonatomic,copy)NSMutableDictionary* selectedDic;

//是否执行了全选
@property(nonatomic,assign) BOOL isSeleteAll;
@property (nonatomic, strong) NSMutableArray *tempAllDataArr;
@end

@implementation TKIMSMSChatView

{
    dispatch_queue_t _messageQueue;
}

-(instancetype)initWithFrame:(CGRect)frame type:(TKIMToolBarType)toolBarType
{
    self = [super initWithFrame:frame];
    if (self) {
        _audioHelper = [[TKIMAudioHelper alloc] init];
        _audioHelper.delegate = self;
        _dataSource = [NSMutableArray array];
        _messageQueue = dispatch_queue_create("com.thinkive.message", NULL);
        _toolBarType = toolBarType;
        [self drawView];
        
        //添加下拉加载更多视图
//        [self refreshHeader];
//        [self refreshfooter];
    }
    return self;
}

/**
 *  @Author lpm, 15-07-27 16:07:41
 *
 *  @brief  绘制界面
 */
-(void)drawView
{

    self.backgroundColor = [TKIMColorHelper stringToColor:@"#EBECED"];
    
    if (_toolBarType==3) {
        _tableView = [[TKIMTableView alloc] initWithFrame:CGRectMake(0, 0,self.width, self.height-HOME_INDICATOR_HEIGHT)];
    }else{
        _tableView = [[TKIMTableView alloc] initWithFrame:CGRectMake(0, 0,self.width, self.height-50-HOME_INDICATOR_HEIGHT)];
    }
    
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    UIView *view  = [UIView new];
    _tableView.tableFooterView = view;
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 5)];
    _tableView.tableHeaderView = headView;
    _tableView.canCancelContentTouches = NO;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundColor = [TKIMColorHelper stringToColor:@"#EBECED"];

    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.allowsSelection=NO;
    _isSeletedState=NO;

    
   

    
    [self addSubview:_tableView];
    [self refreshfooter];
    
    if (3 ==_toolBarType) {
        //键盘工具栏
        [self addSubview:self.deleteBtn];
        _deleteBtn.frame=CGRectMake(0,  self.height-50-HOME_INDICATOR_HEIGHT, self.width, 50);
        _deleteBtn.hidden=YES;
    }else{
        _toolBar = [[TKIMToolBar alloc] initWithFrame:CGRectMake(0,  _tableView.bottom, self.width, 50) toolBarType:_toolBarType];
        _toolBar.delegate = self;
        [self addSubview:_toolBar];
    }
    
    
    
}


#pragma 下拉加载

////创建下拉加载更多历史数据视图
//-(TKIMRefreshHeaderView *)refreshHeader
//{
//    __weak typeof(self) weakSelf = self;
//    if (!_refreshHeader) {
//        _refreshHeader = [[TKIMRefreshHeaderView alloc] initWithScrollView:weakSelf.tableView beginLoadMoreBlock:^(TKIMRefreshHeaderView * refreshHeader) {
//            
//            if([weakSelf.delegate respondsToSelector:@selector(requestMoreHistoryMessagecount:historyDataBlock:)]){
//                [weakSelf.delegate requestMoreHistoryMessagecount:weakSelf.dataSource.count+15 historyDataBlock:^(NSMutableArray * historyData) {
//                    
//                    if (weakSelf.dataSource.count < historyData.count) {
//                        [weakSelf reloadHistoryList:historyData];
//                        refreshHeader.haveMoreHistoryData = YES;
//                    }else{
//                        refreshHeader.haveMoreHistoryData = NO;
//                    }
//                    //刷新视图停止刷新
//                    [refreshHeader endRefresh];
//                }];
//            }
//        }];
//    }
//    return _refreshHeader;
//}






//创建上拉加载更多历史数据视图
-(TKIMRefreshFooterView *)refreshfooter
{
    __weak typeof(self) weakSelf = self;
    if (!_refresfooter) {
        _refresfooter =[[TKIMRefreshFooterView alloc] initWithScrollView:weakSelf.tableView beginLoadMoreBlock:^(TKIMRefreshFooterView *refreshFooterView) {
            if (!_isSeletedState) {
                if([weakSelf.delegate respondsToSelector:@selector(requestMoreHistoryMessagecount:historyDataBlock:)]){
                    [weakSelf.delegate requestMoreHistoryMessagecount:weakSelf.dataSource.count+15 historyDataBlock:^(NSMutableArray * historyData) {
                        if (weakSelf.dataSource.count < historyData.count) {
                            [weakSelf reloadList:historyData isNeedTime:YES];
                            refreshFooterView.haveMoreData = YES;
                        }else{
                            refreshFooterView.haveMoreData = NO;
                        }
                        //刷新视图停止刷新
                        [refreshFooterView endRefresh];
                    }];
                }
            }else{
               [refreshFooterView endRefresh];
            }
            

            
            
        }];
    }
    _refresfooter.haveMoreData=YES;
    return _refresfooter;
}



#pragma mark Table委托
/**
 *  @Author lpm, 15-07-27 16:07:06
 *
 *  @brief
 *
 *  @param tableView
 *  @param section
 *
 *  @return
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}


/**
 *  @Author lpm, 15-07-27 16:07:12
 *
 *  @brief
 *
 *  @param tableView
 *  @param indexPath
 *
 *  @return
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < _dataSource.count)
    {
        NSObject *obj = _dataSource[indexPath.row];
        if ([obj isKindOfClass:[NSString class]])
        {
            NSString *identifier = [NSString stringWithFormat:@"time"];
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.backgroundColor = [UIColor clearColor];
            }
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.text = (NSString *)obj;
            cell.textLabel.font = [UIFont systemFontOfSize:13.0f];
            cell.textLabel.textColor = [UIColor grayColor];
            return cell;
        }
        else
        {
            
            TKChatMessageModle* tempmodle=(TKChatMessageModle *)obj;
            
            TKIMMessage *message = tempmodle.msg;
            TKIMMsgType type =  message.type;
            
            NSDictionary *extDict = message.ext;

            if ([[extDict allKeys] containsObject:@"isReaded"]) {
                if ([extDict[@"isReaded"]  isEqual: @(1)]) {
                    message.state = TKIMMsgSendStateRead;
                }
            }
            
            NSString *identifier = [NSString stringWithFormat:@"MessageCell==%ld",(long)type];
            
            if (type==TKIMMsgTypeRichTxt||type==TKIMMsgTypeDTW) {
                
                TKIMMsgExtType type2=message.msgType;
                if (TKIMMsgExtYCSMS==type2) {
                    identifier = [NSString stringWithFormat:@"MessageCell==%ld",(long)type2];
                }
            }
            
            
            TKIMChatViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell)
            {
                cell = [[TKIMChatViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier msg:message];
                cell.backgroundColor = [UIColor clearColor];
                
                
            }
            else
            {
                [cell setMessage:message];
            }
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.isShowSeleted=self.isSeletedState;//是否展示选择样式
            [cell choseSeletedImageState:tempmodle.isSeleted];
       
            if (message.type == TKIMMsgTypeTxt) {
                message.state = TKIMMsgSendStateRead;
                [[TKIMDBManager shareInstance] updateMsg:message];
            }
            
            return cell;
        }
    }
    
    return  [[UITableViewCell alloc] init];
//    return nil;
}


/**
 *  @Author lpm, 15-07-27 19:07:41
 *
 *  @brief
 *
 *  @param tableView
 *  @param indexPath
 *
 *  @return
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row<_dataSource.count) {
        NSObject *obj = _dataSource[indexPath.row];
        
        if (![obj isKindOfClass:[NSString class]])
        {
            TKChatMessageModle* tempmodle=(TKChatMessageModle *)obj;
            TKIMMessage *message = tempmodle.msg;
            CGFloat height = message.size.height;
            if (height == 0.)
            {
                CGFloat h =[TKIMChatViewCell heightForRow:message];
                return h + 25;
            }
            else
            {
                if(message.type == TKIMMsgTypeDTW){
                     return message.size.height + 25;
                }else{
                     return message.size.height;
                }
            }
        }
        
        return 20;
    }else{
        return 0;
    }
    

}



#pragma mark--滑动删除需要实现的方法
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row<_dataSource.count) {
        NSObject *obj = _dataSource[indexPath.row];
        if (![obj isKindOfClass:[NSString class]])
        {
          return YES;
        }else{
            return NO;
        }
    }else{
    
        return NO;
      
    }
    

    
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) { //具体的删除实现
        if (indexPath.row < [self.dataSource count]) {
            
           
            
            NSObject *obj = _dataSource[indexPath.row];
            if (![obj isKindOfClass:[NSString class]])
            {
                TKChatMessageModle* tempmodle=[self.dataSource objectAtIndex:indexPath.row];
                TKIMMessage *msg = tempmodle.msg;
                
               [[TKIMManager shareInstance] removeMessage:msg];
                
                
                NSInteger index=indexPath.row-1;
                if (index>=0&&index<[self.dataSource count]) {
                    
                    NSObject *obj2 = _dataSource[index];
                    if (![obj2 isKindOfClass:[NSString class]])
                    {//当前删除条的上一条是不是时间，不是时间直接执行删除操作
                         [self.dataSource removeObject:obj];
                         [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                        
                    }else{//当前选中行上一条是时间，就判断当前行的下一条数据
                         NSInteger downindex=indexPath.row+1;
                        if (downindex>=0&&downindex<[self.dataSource count]){
                            
                            NSObject *obj3 = _dataSource[downindex];
                            if (![obj3 isKindOfClass:[NSString class]])
                            {//当前行下一条不是时间就删除但前行就行
                                
                                [self.dataSource removeObject:obj];
                                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
                                
                            }else{//当前行下一条是时间的话就删除当前行和上一行时间
                                
                               [tableView beginUpdates];
                                NSArray * arr =[NSArray arrayWithObjects:indexPath,[NSIndexPath indexPathForRow:index inSection:indexPath.section],nil];
                                NSMutableIndexSet* set = [[NSMutableIndexSet alloc] init];
                                for (NSIndexPath *temppath in arr) {
                                    [set addIndex:temppath.row];
                                }
                                [self.dataSource removeObjectsAtIndexes:set];
                                [tableView deleteRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
                                 [tableView endUpdates];
                                
                            }
                                
                        }else{//如果没有下一条数据
                        
                            NSInteger index=indexPath.row-1;
                            if (index>=0&&index<[self.dataSource count]) {
                                NSObject *obj4 = _dataSource[index];
                                if ([obj4 isKindOfClass:[NSString class]])
                                {//判断上一条数据,上一条是时间的话连时间一起删除否则只删除当前行
                                
                                    NSArray * arr =[NSArray arrayWithObjects:indexPath,[NSIndexPath indexPathForRow:index inSection:indexPath.section],nil];
                                    
                                    NSMutableIndexSet* set = [[NSMutableIndexSet alloc] init];
                                    for (NSIndexPath *temppath in arr) {
                                        [set addIndex:temppath.row];
                                    }
                                    
                                    [self.dataSource removeObjectsAtIndexes:set];
                                    [tableView deleteRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
                                    
                                }
                            }else{
                                [self.dataSource removeObject:obj];
                                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                            }
                            
                        
                        
                        }
                            
                            
                        }
                    
                }else{
                
                    [self.dataSource removeObject:obj];
                    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                
               
            }

            
        }
        

        
    }
}


#pragma mark--多选删除需要的实现的代理
////编辑样式
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.editing)
    {
        return UITableViewCellEditingStyleDelete| UITableViewCellEditingStyleInsert;
    }
    else
    {
        return UITableViewCellEditingStyleDelete;
    }
}

//添加一项
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 
    if (_isSeletedState) {
        NSObject *obj = _dataSource[indexPath.row];
        if (![obj isKindOfClass:[NSString class]])
        {
          TKIMChatViewCell * cell= [tableView cellForRowAtIndexPath:indexPath];
          TKChatMessageModle* tempmodle=[self.dataSource objectAtIndex:indexPath.row];
          tempmodle.isSeleted=!tempmodle.isSeleted;
          [cell choseSeletedImageState:tempmodle.isSeleted];
          [self cellClickAction:tempmodle.isSeleted index:indexPath];
        }
    }else{
        NSObject *obj = _dataSource[indexPath.row];
        if (![obj isKindOfClass:[NSString class]])
        {
            TKChatMessageModle* tempmodle=(TKChatMessageModle*)obj;
            TKIMMessage *message = tempmodle.msg;
            if (message.msgType==TKIMMsgExtYCSMS) {
                TKIMSrvRichMessage* msg=(TKIMSrvRichMessage*)message;
                //先更新消息的状态
                msg.state = TKIMMsgSendStateRead;
                _dataSource[indexPath.row]=msg;
                [[TKIMDBManager shareInstance] updateMsg:msg];
                //后执行跳转操作
                [self routerEventWithName:TKIMMsgClickEvent userInfo:msg];
                [self routerEventWithName:TKIMSrvTemplOnclick userInfo:msg.items[0]];
            }
        }
    }
}

-(void)cellClickAction:(BOOL)flag index:(NSIndexPath*)path{
    
    if (flag) {
        [self deleteNormalStyle];
        [self.selectedDic setObject:self.dataSource[path.row] forKey:path];
    }else{
        [self.selectedDic removeObjectForKey:path];
        if (!(self.selectedDic.allKeys&&self.selectedDic.allKeys.count>0)) {
            [self deleteDisableStyle];
        }
    }


}



/**
 *  @Author lpm, 15-11-19 11:11:28
 *
 *  @brief
 *
 *  @param touches
 *  @param event
 */
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self tableOnTouch];
}


/**
 *  @Author lpm, 15-11-19 11:11:28
 *
 *  @brief
 *
 *  @param touches
 *  @param event
 */
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self tableOnTouch];
}

#pragma mark 工具栏代理


/**
 *  @Author lpm, 15-07-28 09:07:53
 *
 *  @brief  键盘显示
 *
 *  @param offset 偏移量
 */
-(void)keyBoardShow:(CGFloat)offset duration:(CGFloat)duration
{
    [UIView animateWithDuration:duration animations:^
     {
         _tableView.frame = CGRectMake(_tableView.left, _tableView.top,_tableView.width, self.height-offset-50);
         
         if (_dataSource.count>0)
         {
             NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
             [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
         }
     }
                     completion:^(BOOL finished)
     {
         
     }];
}


/**
 *  @Author lpm, 15-07-28 09:07:12
 *
 *  @brief  键盘消失
 *
 *  @param offset 偏移量
 */
-(void)keyBoardHide:(CGFloat)offset duration:(CGFloat)duration
{
    [UIView animateWithDuration:duration animations:^
     {
         _tableView.frame = CGRectMake(_tableView.left, _tableView.top,_tableView.width, self.height-50);
     }];
}


/**
 *  @Author lpm, 15-07-28 18:07:41
 *
 *  @brief  接收服务器消息
 *
 *  @param msg
 */
-(void)receiveMsg:(id)msg
{
    if (msg)
    {
//        dispatch_barrier_async(_messageQueue, ^
//                               {
//                                   TKIMMessage *txtMsg = (TKIMMessage *)msg;
//                                   if (txtMsg.type == TKIMMsgTypeTxt)
//                                   {
//                                       txtMsg.attrText = [self filterTxtMessage:txtMsg.text];
//                                   }
//
//                                   TKChatMessageModle * data=[[TKChatMessageModle alloc] init];
//                                   data.msg=txtMsg;
//
//                                   [_dataSource insertObject:data atIndex:0];
//                                   dispatch_async(dispatch_get_main_queue(), ^
//                                                  {
//                                                      [_tableView reloadData];
//                                                  });
//                               });
        
        [self.tempAllDataArr addObject:msg];
        
        NSMutableArray *tempDataSource = [NSMutableArray arrayWithArray:self.tempAllDataArr];
        [self reloadList:tempDataSource isNeedTime:YES];
    }
}
/**
 *  刷新历史记录
 *
 *  @param dataList 数据源
 *  @param row      滚动到历史消息位置
 */
-(void)reloadHistoryList:(NSMutableArray *)dataList
{
    dispatch_barrier_async(_messageQueue, ^{
        NSMutableArray *formatArray = [[NSMutableArray alloc] init];
        for (NSInteger i=0; i<dataList.count; i++) {
            
            TKChatMessageModle* tempmodle=dataList[i];
            
            if (![[tempmodle class] isSubclassOfClass:[NSString class]]) {
                
                TKIMMessage*message=tempmodle.msg;
                
                NSDate *createDate = [TKIMDateHelper stringToDate:message.time];
                NSTimeInterval tempDate = [createDate timeIntervalSinceDate:self.chatTagDate];
//                if (tempDate > 60 || tempDate < -60 || (self.chatTagDate == nil)) {
                if (tempDate > 120 || tempDate < -120 || (self.chatTagDate == nil)) {
                    [formatArray addObject:[TKIMDateHelper  formattedTime:message.time]];
                    self.chatTagDate = createDate;
                }
                //不需要聊天时间信息了
                if (message.type == TKIMMsgTypeTxt)
                {
                    message.attrText = [self filterTxtMessage:message.text];
                }
                tempmodle.msg=message;
                [formatArray addObject:tempmodle];
                
                
            }
        }
        self.dataSource = formatArray;
        
        CGFloat oldHeight = self.tableView.contentSize.height;
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
            self.tableView.contentOffset = CGPointMake(0, self.tableView.contentSize.height - oldHeight);
        });
    });
    
}


/**
 *  @Author lpm, 15-07-28 18:07:41
 *
 *  @brief  刷新列表
 *
 *  @param msg
 */
-(void)reloadList:(NSMutableArray *)dataList isNeedTime:(BOOL)isneedtime
{
    if (dataList)
    {
        self.tempAllDataArr = [[NSMutableArray alloc]initWithArray:dataList];
        dispatch_barrier_async(_messageQueue, ^{
            NSMutableArray*dataList1=dataList;
            NSMutableArray *formatArray = [[NSMutableArray alloc] init];
            for (NSInteger i=dataList1.count-1; i>=0; i--) {
                TKIMMessage* message=dataList1[i];
                
                if (![[message class] isSubclassOfClass:[NSString class]] && message.type != TKIMMsgTypeCmd) {
                    NSDate *createDate = [TKIMDateHelper stringToDate:message.time];
                    NSTimeInterval tempDate = [createDate timeIntervalSinceDate:self.chatTagDate];
//                    if (tempDate > 60 || tempDate < -60 || (self.chatTagDate == nil)) {
                    if (tempDate > 120 || tempDate < -120 || (self.chatTagDate == nil)) {
                        [formatArray addObject:[TKIMDateHelper formattedTime:message.time]];
                        self.chatTagDate = createDate;
                    }
                    //不需要聊天时间信息了
                    if (message.type == TKIMMsgTypeTxt)
                    {
                        message.attrText = [self filterTxtMessage:message.text];
                    }
                    
                    if (message) {
                        TKChatMessageModle* model=[[TKChatMessageModle alloc] init];
                        model.msg=message;
                        model.isSeleted=NO;
                        [formatArray addObject:model];
                    }
                }
            }
            
            self.dataSource =formatArray;
            dispatch_async(dispatch_get_main_queue(), ^{
                [_tableView reloadData];
            });
        });
    }
    else
    {
        [_tableView reloadData];
    }
}




- (NSDate *)chatTagDate
{
    if (_chatTagDate == nil)
    {
        _chatTagDate = [TKIMDateHelper dateWithTimeIntervalInMilliSecondSince1970:0];
    }
    return _chatTagDate;
}


/**
 *  @Author lpm, 15-07-29 16:07:21
 *
 *  @brief  滚动时收起键盘
 *
 *  @param scrollView
 */
-(void)tableOnTouch
{
    [_toolBar resignInputFirstResponder];
    if ([UIMenuController sharedMenuController].isMenuVisible)
    {
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    }
}


/**
 *  @Author lpm, 15-07-29 16:07:38
 *
 *  @brief  收起键盘
 */
-(void)resignInputFirstResponder
{
    [_toolBar resignInputFirstResponder];
}


#pragma mark 消息发送相关



/**
 *  @Author lpm, 15-10-27 09:10:48
 *
 *  @brief  路由事件
 *
 *  @param eventName 事件名
 *  @param userInfo 参数
 */
-(void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo
{
    //播放声音
    if ([eventName isEqualToString:TKIMAudioEvent]){
        [self playAudio:userInfo];
    }
    //录音
    else if([eventName isEqualToString:TKAudioRecordEvent]){
        [self recordAudio:userInfo];
    }
    //发送图片
    else if([eventName isEqualToString:TKIMImageSelectedEvent]){
        [self sendImages:(NSArray *)userInfo];
    }
    //发送声音 || 发送拍照图片
    else if([eventName isEqualToString:TKAudioSendEvent]||[eventName isEqualToString:TKIMSendPhotoEvent]){
        [self sendMessage:(TKIMMessage *)userInfo];
    }
    else if([eventName isEqualToString:TKIMSendLocationEvent]){
        [self jumpToLocationCtl];
    }
    //发送录像
    else if([eventName isEqualToString:TKIMVideoSelectedEvent]){
        [self sendVideos:(TKIMVideoMessage *)userInfo];
    }
    //长按消息
    else if ([eventName isEqualToString:TKIMMsgLongPressEvent]){
        TKIMMessage *msg = userInfo[@"msg"];
        UIView *view = userInfo[@"view"];
        [self showMenu:msg view:(TKIMBaseMsgView *)view];
    }
    //菜单工具栏事件
    else if ([eventName isEqualToString:TKIMMenuBarOnclickEvent]){
        [self menuBarOnclick:userInfo];
        
    }
    else{
        [super routerEventWithName:eventName userInfo:userInfo];
    }
}





/**
 *  @Author lpm, 16-05-10 11:05:39
 *
 *  @brief  播放声音
 *
 *  @param userInfo
 */
-(void)playAudio:(NSDictionary *)userInfo
{
    NSString *state = userInfo[@"state"];
    TKIMAudioMessage *audio = userInfo[@"msg"];
    TKIMAudioMsgView *msgView = userInfo[@"msgView"];
    //如果是播放
    if ([state isEqualToString:@"play"])
    {
        //先停止当前播放的声音
        if (_currentAudio)
        {
            [_audioHelper stopPlay];
            [_currentAudio stopPlaying];
        }
        _currentAudio = msgView;
        [_audioHelper play:[NSURL fileURLWithPath:audio.localUrl]];
    }
    else
    {
        [_audioHelper stopPlay];
        _currentAudio = nil;
    }
}


/**
 *  @Author lpm, 16-05-10 11:05:00
 *
 *  @brief  录音
 *
 *  @param userInfo
 */
-(void)recordAudio:(NSDictionary *)userInfo
{
    //先停止当前播放的声音
    if (_currentAudio)
    {
        [_audioHelper stopPlay];
        [_currentAudio stopPlaying];
    }
}


/**
 *  @Author lpm, 16-05-10 11:05:25
 *
 *  @brief  菜单被点击
 *
 *  @param userInfo
 */
-(void)menuBarOnclick:(NSDictionary *)userInfo
{
    TKIMMessage *msg = [[TKIMMessage alloc] init];
    msg.text = (NSString *)userInfo;
    msg.isOrder = YES;
    msg.isSender = YES;
    [self sendMessage:msg];
    [self tip];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tip removeFromSuperview];
    });
}

/**
 *  @Author lpm, 16-01-08 19:01:06
 *
 *  @brief  跳转到定位的控制器
 */
-(void)jumpToLocationCtl
{
    [self routerEventWithName:TKIMLocationClickEvent userInfo:nil];
}


/**
 *  @Author lpm, 15-10-27 15:10:23
 *
 *  @brief  发送位置
 *
 *  @param location
 */
-(void)sendLocation:(TKIMLocationMessage *)location
{
    location.isSender = YES;
    [self sendMessage:(TKIMMessage *)location];
}

/**
 *  @Author lpm, 15-10-21 17:10:40
 *
 *  @brief  长按单元格
 *
 *  @param tap
 */
-(void)showMenu:(TKIMMessage *)msg view:(TKIMBaseMsgView *)view
{
    if (msg.state == TKIMMsgSendStateSending)
    {
        return;
    }
    
    _selectMessage = msg;
    
    [view becomeFirstResponder];
    
    UIMenuController *menuCtrl = [UIMenuController sharedMenuController];
    [menuCtrl setTargetRect:view.backgroundImageView.frame inView:view];
    
    if (msg.state == TKIMMsgSendStateSendFail)
    {
        UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteMsg:)];
        UIMenuItem *reSend = [[UIMenuItem alloc] initWithTitle:@"重发" action:@selector(reSend:)];
        [menuCtrl setMenuItems:@[delete,reSend]];
    }
    else
    {
        UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteMsg:)];
        UIMenuItem *copy = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyMsg:)];
        
        if (msg.type == TKIMMsgTypeTxt || msg.type == TKIMMsgTypeDTW)
        {
            [menuCtrl setMenuItems:@[delete,copy]];
        }
        else
        {
            [menuCtrl setMenuItems:@[delete]];
        }
    }
    
    [menuCtrl setMenuVisible:YES animated:YES];
}


/**
 *  @Author lpm, 15-11-19 11:11:54
 *
 *  @brief  复制
 *
 *  @param sender
 */
- (void)copyMsg:(id)sender
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if (_selectMessage) {
        pasteboard.string = _selectMessage.text;
    }
    _selectMessage = nil;
}


/**
 *  @Author lpm, 15-11-19 11:11:13
 *
 *  @brief  删除消息
 *
 *  @param item
 */
-(void)deleteMsg:(UIMenuItem *)item
{
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    [[TKIMManager shareInstance] removeMessage:_selectMessage];
    
    //add by yujinshi for delete row crash
    int row = -1;
    for(id chatMsg in _dataSource){
        ++row;
        if (chatMsg && [chatMsg isKindOfClass:[TKChatMessageModle class]]){
            TKChatMessageModle* imMsg = (TKChatMessageModle*)chatMsg;
            if([imMsg.msg.messageId isEqualToString:_selectMessage.messageId]){
                break;
            }
        }
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
    //[_dataSource removeObject:_selectMessage];
    [_dataSource removeObjectAtIndex:row];
    
    if ([_tableView numberOfRowsInSection:indexPath.section] == 1) {
        [_tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section]withRowAnimation:UITableViewRowAnimationFade];
    } else {
        [_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    _selectMessage = nil;
}


/**
 *  @Author lpm, 15-11-19 11:11:13
 *
 *  @brief  重发消息
 *
 *  @param item
 */
-(void)reSend:(UIMenuItem *)item
{
    _selectMessage.state = TKIMMsgSendStateSending;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[_dataSource indexOfObject:_selectMessage] inSection:0];
    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [[TKIMManager shareInstance] resendMessage:_selectMessage];
    _selectMessage = nil;
}


/**
 *  @Author lpm, 15-11-19 11:11:44
 *
 *  @brief  放行响应事件
 *
 *  @param action
 *  @param sender
 *
 *  @return
 */
-(BOOL) canPerformAction:(SEL)action withSender:(id)sender{
    if (action == @selector(deleteMsg:)||action == @selector(reSend:)||action == @selector(copyMsg:)) {
        return YES;
    }
    return NO; //隐藏系统默认的菜单项
}


/**
 *  @Author lpm, 15-07-27 16:07:21
 *
 *  @brief  发送消息
 *
 *  @param message
 */
-(void)sendTxt:(NSString *)message
{
    TKIMMessage *msg =  [self getMsgObject:message isSender:YES];
    msg.attrText = [self filterTxtMessage:msg.text];
    [self sendMessage:msg];
}


/**
 *  @Author lpm, 15-10-22 20:10:27
 *
 *  @brief  发送图片
 *
 *  @param images
 */
-(void)sendImages:(NSArray *)images
{
    [images enumerateObjectsUsingBlock:^(id  obj, NSUInteger idx, BOOL *  stop)
     {
         TKIMPhotoModel *photo = (TKIMPhotoModel *)obj;
         TKIMImageMessage *msg = [[TKIMImageMessage alloc] init];
         msg.isSender = YES;
         msg.thumbImage = photo.thumbImage;
         msg.originImage = photo.originImage;
         [self sendMessage:msg];
     }];
}


/**
 *  @Author lpm, 15-10-23 10:10:33
 *
 *  @brief  发消息
 *
 *  @param msg
 */
-(void)sendVideos:(TKIMVideoMessage *)video
{
    [self sendMessage:video];
}


/**
 *  @Author lpm, 15-07-29 10:07:04
 *
 *  @brief  发送系统消息
 *
 *  @param message
 */
-(void)sendSysMsg:(NSString *)message
{
    dispatch_barrier_async(_messageQueue, ^{
        [_dataSource addObject:[self getMsgObject:message isSender:NO]];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
            [_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        });
    });
}


/**
 *  @Author lpm, 15-10-23 10:10:33
 *
 *  @brief  发消息
 *
 *  @param msg
 */
-(void)sendMessage:(TKIMMessage *)msg
{
    if (_delegate && [_delegate respondsToSelector:@selector(sendMessage:)])
    {
        [_delegate sendMessage:msg];
    }
    
    if (!msg.isOrder)
    {
        msg.fromUser = [TKIMSDKHelper getLoginUserName];
        dispatch_barrier_async(_messageQueue, ^{
            [_dataSource addObject:msg];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_tableView reloadData];
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
                [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            });
        });
    }
}



/**
 *  @Author lpm, 15-07-28 18:07:41
 *
 *  @brief  更新消息状态
 *
 *  @param msg
 */
-(void)updateMsg:(TKIMMessage *)message
{
    //    NSLog(@"update");
    if (message)
    {
        dispatch_barrier_async(_messageQueue, ^ {
            for (NSObject *obj in _dataSource)
            {
                if (![obj isKindOfClass:[NSString class]])
                {
                    NSInteger index = [_dataSource indexOfObject:obj];
                    TKIMMessage *msg = (TKIMMessage *)obj;
                    
                    if([obj isKindOfClass:[TKIMMessage class]])
                    {
                        msg = (TKIMMessage *)obj;
                    }
                    else if([obj isKindOfClass:[TKChatMessageModle class]])
                    {
                        TKChatMessageModle *messgaeModel = (TKChatMessageModle *)obj;
                        msg = messgaeModel.msg;
                    }
                    
                    
                    if ([message.messageId isEqualToString:msg.messageId])
                    {
                        message.size = msg.size;
                        
                        if (message.type == TKIMMsgTypeTxt)
                        {
                            message.attrText = [self filterTxtMessage:message.text];
                        }
                        
                        [_dataSource replaceObjectAtIndex:index withObject:message];
                        
                        dispatch_async(dispatch_get_main_queue(), ^
                                       {
                                           //                    [_tableView beginUpdates];
                                           //                    [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]]     withRowAnimation:UITableViewRowAnimationNone];
                                           //                    [_tableView endUpdates];
                                           [_tableView reloadData];
                                           //                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
                                           //                    [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                                           
                                       });
                        break;
                    }
                }
            }
        });
    }
}



/**
 *  @Author lpm, 15-07-29 10:07:21
 *
 *  @brief  发送消息s
 *
 *  @param message  消息
 *  @param userType 用户类型
 */
-(TKIMMessage *)getMsgObject:(NSString *)message isSender:(BOOL)isSender
{
    TKIMMessage *msg = [[TKIMMessage alloc] init];
    msg.text = message;
    msg.isSender = isSender;
    return msg;
}


/**
 *  @Author lpm, 15-10-27 09:10:14
 *
 *  @brief  播放完成
 *
 *  @param flag 是否播放成功
 */
-(void)audioPlayerDidFinishPlaying:(BOOL)flag
{
    if (_currentAudio)
    {
        [_currentAudio stopPlaying];
        _currentAudio = nil;
    }
}


#pragma mark 文本消息过滤

/**
 *  @Author lpm, 15-12-04 14:12:15
 *
 *  @brief  表情
 *
 *  @return
 */
-(NSDictionary *)emotion
{
    if (!_emotion)
    {
        NSString *emotionPlist = TKIMSrcName(@"TKIMEmotion.json");
        NSData *data = [NSData dataWithContentsOfFile:emotionPlist];
        NSDictionary *dic = (NSDictionary *)[TKIMDataHelper dataToObject:data];
        _emotion = dic[@"emotion"];
    }
    return _emotion;
}

/**
 *  @Author lpm, 15-12-04 14:12:23
 *
 *  @brief  过滤文字消息
 *
 *  @param text
 *
 *  @return
 */
-(NSAttributedString *)filterTxtMessage:(NSString *)text
{
    return [self filterTxtMessage:text font:15 imageBounds:CGRectMake(0, -6, 25,25)];
}
/**
 *  @Author lpm, 15-12-04 14:12:23
 *
 *  @brief  过滤文字消息
 *
 *  @param text
 *
 *  @return
 */
-(NSAttributedString *)filterTxtMessage:(NSString *)text font:(CGFloat)f imageBounds:(CGRect)bounds
{
    if (!text || ![text isKindOfClass:[NSString class]]){
        return nil;
    }
    NSString *emotionPlist = TKIMSrcName(@"TKIMEmotion.json");
    NSData *data = [NSData dataWithContentsOfFile:emotionPlist];
    NSDictionary *dic = (NSDictionary *)[TKIMDataHelper dataToObject:data];
    NSDictionary *emotion = dic[@"emotion"];
    
    NSMutableArray *textArray = [NSMutableArray array];
    NSMutableArray *imgArray = [NSMutableArray array];
    
    NSRange range = [text rangeOfString:@"["];
    if (range.location != NSNotFound){
        NSDictionary *userInfo =  [TKIMStringHelper replaceString:text from:@"\\[@emoji_\\d+\\.gif\\]" to:@"┠┨" ];
        NSString *textCopy = userInfo[@"replaceString"];
        textArray = (NSMutableArray *)[textCopy componentsSeparatedByString:@"┠┨"];
        NSArray *ts =  userInfo[@"matchResults"];
        if (emotion){
            //遍历消息文字数组
            for (NSString *value in ts){
                NSString *imageName = emotion[value];
                if (imageName){
                    [imgArray addObject:imageName];
                }
            }
        }
    }
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
    
    if (imgArray && imgArray.count == 0){
        NSAttributedString *substr =[[NSAttributedString alloc] initWithString:text];
        [attributedText appendAttributedString:substr];
    }else{
        for (NSUInteger i = 0; i < textArray.count; i++){
            NSAttributedString *substr =[[NSAttributedString alloc] initWithString:[textArray objectAtIndex:i]];
            [attributedText appendAttributedString:substr];
            if (i != textArray.count - 1){
                NSTextAttachment *attch = [[NSTextAttachment alloc] init];
                NSInteger count = imgArray.count -1;
                if(count < i){
                    continue;
                }
                
                NSString *url =  [NSString stringWithFormat:@"%@",imgArray[i]];
                NSString *imgUrl = TKIMSrcName(url);
                NSString *str = [[[imgUrl componentsSeparatedByString:@"/"] lastObject] componentsSeparatedByString:@"."][0];
                NSString *x = [NSString stringWithFormat:@"%@",str];
//                UIImage *image = [UIImage sd_animatedGIFNamed:x];
                NSData *gifData = [NSData dataWithContentsOfFile:imgUrl];
                UIImage *image = [UIImage sd_imageWithGIFData:gifData];
                attch.bounds = bounds;
                attch.image = image;
                [attch.image  setAccessibilityIdentifier:url];
                NSAttributedString *substr2 = [NSAttributedString attributedStringWithAttachment:attch];
                [attributedText appendAttributedString:substr2];
            }
        }
    }
    
    //给文字中的链接做标记
//    [TKIMAttributedLabelURL detectLinks:attributedText];
    
    // 一定要设置字体,保证计算出来的尺寸是正确的
    UIFont *font = [UIFont systemFontOfSize:f];
    [attributedText addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attributedText.length)];
    return attributedText;
}

///**
// *  @Author lpm, 15-12-04 14:12:23
// *
// *  @brief  过滤文字消息
// *
// *  @param text
// *
// *  @return
// */
//-(NSAttributedString *)filterTxtMessage:(NSString *)text
//{
//    if (!text || ![text isKindOfClass:[NSString class]])
//    {
//        return nil;
//    }
//    NSMutableArray *textArray = [NSMutableArray array];
//    NSMutableArray *imgArray = [NSMutableArray array];
//    
//    NSRange range = [text rangeOfString:@"["];
//    if (range.location != NSNotFound)
//    {
//        
//        NSDictionary *userInfo =  [TKIMStringHelper replaceString:text from:@"\\[@emoji_\\d+\\.gif\\]" to:@"┠┨" ];
//        NSString *textCopy = userInfo[@"replaceString"];
//        textArray = (NSMutableArray *)[textCopy componentsSeparatedByString:@"┠┨"];
//        NSArray *ts =  userInfo[@"matchResults"];
//        if (self.emotion)
//        {
//            //遍历消息文字数组
//            for (NSString *value in ts)
//            {
//                
//                NSString *imageName = self.emotion[value];
//                if (imageName)
//                {
//                    [imgArray addObject:imageName];
//                }
//            }
//        }
//    }
//    
//    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
//    
//    if (imgArray && imgArray.count == 0)
//    {
//        NSAttributedString *substr =[[NSAttributedString alloc] initWithString:text];
//        [attributedText appendAttributedString:substr];
//    }
//    else
//    {
//        for (NSUInteger i = 0; i < textArray.count; i++)
//        {
//            NSAttributedString *substr =[[NSAttributedString alloc] initWithString:[textArray objectAtIndex:i]];
//            [attributedText appendAttributedString:substr];
//            if (i != textArray.count - 1)
//            {
//                NSTextAttachment *attch = [[NSTextAttachment alloc] init];
//                NSInteger count = imgArray.count -1;
//                if(count < i)
//                {
//                    continue;
//                }
//                
//                NSString *url =  [NSString stringWithFormat:@"%@",imgArray[i]];
//                NSString *imgUrl = TKIMSrcName(url);
//                NSString *str = [[[imgUrl componentsSeparatedByString:@"/"] lastObject] componentsSeparatedByString:@"."][0];
//                NSString *x = [NSString stringWithFormat:@"%@",str];
//                UIImage *image = [UIImage sd_animatedGIFNamed2:x];
//                attch.bounds = CGRectMake(0, -6, 25,25);
//                attch.image = image;
//                NSAttributedString *substr2 = [NSAttributedString attributedStringWithAttachment:attch];
//                [attributedText appendAttributedString:substr2];
//            }
//        }
//    }
//    // 一定要设置字体,保证计算出来的尺寸是正确的
//    UIFont *font = [UIFont systemFontOfSize:15.0f];
//    [attributedText addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attributedText.length)];
//    return attributedText;
//}


#pragma mark 属性
-(TKIMAcceptOrderTip *)tip
{
    if (!_tip) {
        TKIMAcceptOrderTip * tip = [[TKIMAcceptOrderTip alloc] initWithFrame:CGRectMake((self.width-150)*0.5, self.height-50-35-15, 150, 35)];
        _tip = tip;
        [self addSubview:_tip];
        [self bringSubviewToFront:_tip];
    }
    return _tip;
}


-(void)setMenusArray:(NSArray *)menusArray
{
    _menusArray = menusArray;
    self.toolBar.menusArray = menusArray;
    if(menusArray.count >0)
    {
        self.toolBar.tooBarType = TKIMToolBarOfiicalType;
    }
}


#pragma mark-删除按钮
//新加的多选按钮
-(void)dochoice:(actionNav)action{
    action(!self.isSeletedState);
    self.isSeleteAll = NO;
    if (!self.isSeletedState) {
        
        self.tableView.height+=50;
        [self.selectedDic removeAllObjects];
        [self deleteDisableStyle];
        
        for (int i = 0; i <self.dataSource.count; i ++) {
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            
            NSObject *obj = _dataSource[indexPath.row];
            
            
            if (![obj isKindOfClass:[NSString class]])
            {
                
                TKIMChatViewCell * cell= [_tableView cellForRowAtIndexPath:indexPath];
                TKChatMessageModle* tempmodle=[self.dataSource objectAtIndex:indexPath.row];
                tempmodle.isSeleted=NO;
                [cell choseSeletedImageState:NO];
                [self cellClickAction:NO index:indexPath];
                
            }
            
        }
        
        
        
        
    }else{
         [self deleteDisableStyle];
        self.tableView.height-=50;
    }
    [UIView animateWithDuration:0.5 animations:^{
        self.deleteBtn.hidden=!self.isSeletedState;
    }];
    [_tableView reloadData];
    
}


-(void)dochoiceAll:(actionNav)action{

    if (self.isSeleteAll) {
        
        for (int i = 0; i <self.dataSource.count; i ++) {
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            
            NSObject *obj = _dataSource[indexPath.row];
            
            
            if (![obj isKindOfClass:[NSString class]])
            {
                
                TKIMChatViewCell * cell= [_tableView cellForRowAtIndexPath:indexPath];
                TKChatMessageModle* tempmodle=[self.dataSource objectAtIndex:indexPath.row];
                tempmodle.isSeleted=NO;
                [cell choseSeletedImageState:NO];
                [self cellClickAction:NO index:indexPath];
                
            }
            
        }
        
        
        
        
        
         self.isSeleteAll=NO;
        
        [self.selectedDic removeAllObjects];
        action(0);
        
        
        
    }else{
        
         [self.selectedDic removeAllObjects];
        for (int i = 0; i <self.dataSource.count; i ++) {
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            
            NSObject *obj = _dataSource[indexPath.row];
            
            
            if (![obj isKindOfClass:[NSString class]])
            {
                
                TKIMChatViewCell * cell= [_tableView cellForRowAtIndexPath:indexPath];
                TKChatMessageModle* tempmodle=[self.dataSource objectAtIndex:indexPath.row];
                tempmodle.isSeleted= YES;
                [cell choseSeletedImageState:YES];
                [self cellClickAction:YES index:indexPath];
                
            }
            
        }
        self.isSeleteAll=YES;
        
        action(1);
        
        
    }
    
    if (self.selectedDic.allKeys&&self.selectedDic.allKeys.count>0) {
        [self deleteNormalStyle];
    }else{
        [self deleteDisableStyle];
    }
}


-(void)deleteDisableStyle{
    _deleteBtn.enabled=NO;
    [_deleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_deleteBtn setBackgroundColor:[UIColor lightGrayColor]];
}

-(void)deleteNormalStyle{
    _deleteBtn.enabled=YES;
    [_deleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_deleteBtn setBackgroundColor:[TKUIHelper colorWithHexString:@"#ff4646"]];
}



#pragma mark--懒加载
-(UIButton*)deleteBtn{
    
    if (_deleteBtn==nil) {
        _deleteBtn=[[UIButton alloc] init];
        UILabel * line=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.width, 1)];
        line.backgroundColor=[TKUIHelper colorWithHexString:@"#e6e6e6"];
        [_deleteBtn addSubview:line];
        [_deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
        [_deleteBtn.titleLabel setFont:[UIFont systemFontOfSize:18]];
        [self deleteDisableStyle];
        [_deleteBtn addTarget:self action:@selector(doDeleteData:) forControlEvents:UIControlEventTouchUpInside];
        _deleteBtn.enabled=NO;
    }
    return _deleteBtn;
}

//删除消息的时候执行的
-(void)doDeleteData:(id)btn{
    
    NSArray * allkeys=self.selectedDic.allKeys;
    if (allkeys&&allkeys.count>0) {
        
         [_tableView beginUpdates];

        NSMutableArray* deteledata=[[NSMutableArray alloc] init];
        for (NSIndexPath * path in allkeys) {
            
            TKChatMessageModle*tempmodle=[self.selectedDic objectForKey:path];
            TKIMMessage * msg=tempmodle.msg;
            [[TKIMManager shareInstance] removeMessage:msg];
            [deteledata addObject:self.dataSource[path.row]];
        }
        [self.dataSource removeObjectsInArray:deteledata];
        
        [_tableView deleteRowsAtIndexPaths:allkeys withRowAnimation:UITableViewRowAnimationAutomatic];
        [_tableView endUpdates];
        
        
        self.tableView.height+=50;
        [self.selectedDic removeAllObjects];
        [UIView animateWithDuration:0.5 animations:^{
            self.deleteBtn.hidden=YES;
        }];
        self.isSeletedState=NO;
        [self reloadHistoryList:self.dataSource];
        [self routerEventWithName:@"Delete_Msg" userInfo:nil];
        
    }
    
    
    
    
}

-(NSMutableDictionary*)selectedDic{
    
    if (_selectedDic==nil) {
        _selectedDic=[[NSMutableDictionary alloc] init];
    }
    
    return _selectedDic;
}



-(void)dealloc
{
    [self.toolBar removeCss];
}


@end
